package com.couldtest.consumerRibbonHystrix.service;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCollapser;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheRemove;
import com.netflix.hystrix.contrib.javanica.cache.annotation.CacheResult;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Future;

/**
 * Created by liguanfu on 2018/6/7.
 */
@Service
public  class ConsumerService {

    @Autowired
    RestTemplate restTemplate;

    /** 调用失败处理逻辑
     * */
    @CacheResult
    @HystrixCommand(fallbackMethod = "fallback")
    public String consumer() {
        System.out.println("进入负载均衡调用");
        return restTemplate.getForObject("http://server-provider/dcx", String.class);
    }

    @CacheRemove(commandKey = "update")
    public String update() {
        System.out.println("进入更新删除缓存");
        return "update";
    }

    /**对特定类型异常做降级处理
     * */
    public String fallback(Throwable throwable) {
        return "fallback";
    }


    /**
     * 异步调用处理
     * */
    @HystrixCommand
    public Future<String> asyncOperate() {
        return new AsyncResult<String>() {
            @Override
            public String invoke() {
                return restTemplate.getForObject("http://server-provider/dcx", String.class);
            }
        };
    }


    /**请求合并
     * */

}
